/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from "react";
import { Cascader } from "antd";

export default class GeographicView extends PureComponent {
  // 格式化区域列表
  formatAreaList = ({ area }) => {
    const list = [];
    const areaLen = area.length;
    this.pIdIndex = {};
    this.cIdIndex = {};
    for (let p = 0; p < areaLen; p++) {
      const arr = area[p] || [];
      const arrLen = arr.length;
      if (arrLen > 0) {
        for (let i = 0; i < arrLen; i++) {
          const { id, pid, name } = arr[i] || {};
          if (!name) continue;
          const data = {
            value: name,
            label: name,
          };
          if (p === 1 && 1 * pid === 0) {
            list.push(data);
            this.pIdIndex[id] = list.length - 1;
          } else if (p === 2) {
            // 市
            const parent = list[this.pIdIndex[pid]];
            parent.children = parent.children || [];
            parent.children.push(data);
            this.cIdIndex[id] = parent.children.length - 1;
          } else {
            // 区
            const currentCity = area[2][pid];
            if (!currentCity) continue;
            const cIndex = this.cIdIndex[pid];
            const pIndex = this.pIdIndex[currentCity.pid];
            const parent = list[pIndex].children[cIndex];
            parent.children = parent.children || [];
            parent.children.push(data);
          }
        }
      }
    }
    this.setState({
      list,
    });
  };

  componentWillMount = () => {
    const { areaList } = window;
    this.formatAreaList({ area: areaList });
  };

  onChange = value => {
    const { onChange } = this.props;
    onChange(value);
  };

  render() {
    const { value } = this.props;
    const { list } = this.state;
    const hasValue = value && !!value.filter(item => !!item).length;
    return (
      <Cascader
        displayRender={label => (hasValue ? (value || label).join(" / ") : "")}
        value={hasValue ? value : ""}
        size="large"
        notFoundContent="未匹配到对应区域"
        showSearch
        expandTrigger="hover"
        options={list}
        onChange={this.onChange}
        placeholder="选择省市区"
      />
    );
  }
}
